package com.xyhuo.leetcode.january;

import com.xyhuo.leetcode.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 路径总和Ⅱ
 * https://leetcode.cn/problems/path-sum-ii/description/
 *
 * @time 2024/1/10
 */
public class PathSum {

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return ans;
        }
        List<Integer> list = new ArrayList<>();
        search(root, targetSum, 0, list);
        return ans;
    }

    private List<List<Integer>> ans = new ArrayList<>();

    private void search(TreeNode root, int targetSum, int sum, List<Integer> list) {
        if (root.left == null && root.right == null) {
            if (sum + root.val == targetSum) {
                List<Integer> ansItem = new ArrayList<>();
                ansItem.addAll(list);
                ansItem.add(root.val);
                ans.add(ansItem);
            }
        }
        if (root.left != null) {
            list.add(root.val);
            search(root.left, targetSum, sum + root.val, list);
            list.remove(list.size() - 1);
        }
        if (root.right != null) {
            list.add(root.val);
            search(root.right, targetSum, sum + root.val, list);
            list.remove(list.size() - 1);
        }
    }
}
